package com.example.limiting.taskmanager2;

import android.content.Context;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by Limiting on 2015/9/24.
 */
public class HttpHelper {
    private Context mContext;
    private String host = "http://192.168.137.74:8080/";
//    private String host = "http://172.26.225.152:8080/";

    String load_all = "mobile/task/list";
    String load_member = "mobile/task/list/member";
    String load_my = "mobile/task/list/my";

    String published = "/pub";
    String finished = "/finished";
    String evaluated = "/evaluate";

    String load_detail = "mobile/task/list";

    String get_workers_part1 = "mobile/";
    String get_workers_part2 = "/follower";

    String publish_to_server = "mobile/task/add";

    String userId;

    public HttpHelper(Context mContext) {
        this.mContext = mContext;

        SharedPreferences sharedPref = mContext.getSharedPreferences("userId",Context.MODE_PRIVATE);
        String savedUserId = sharedPref.getString("userId","");

        if (!savedUserId.isEmpty()){
            userId = savedUserId;
        }else {
            Log.e("sharePref","no userId");
        }

    }

    public String OpenURL(String myurl) throws IOException {
        InputStream is = null;
        try{
            URL url = new URL(myurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(1000 /* milliseconds */);
            conn.setConnectTimeout(1500 /* milliseconds */);

            conn.setRequestMethod("POST");
//            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("contentType", "UTF-8");
            conn.setDoInput(true);
            // Starts the query
            conn.connect();


            int response = conn.getResponseCode();
            Log.d("OpenURL", "The response is: " + response);
            is = conn.getInputStream();

            // Convert the InputStream into a string
            String contentAsString = readIt(is);

            Log.e("OpenUrl",contentAsString);
//            Log.e("OpenUrl", String.valueOf(contentAsString.length()));
            return contentAsString;
        }catch (IOException e){
//            Toast.makeText(mContext, "Please check your network", Toast.LENGTH_SHORT).show();
//            showToast(mContext,"Please check your network");
            e.printStackTrace();
        }
        finally {
            if (is != null) {
                is.close();
            }
        }
        return "";
    }

    // Reads an InputStream and converts it to a String.
    public String readIt(InputStream stream) throws IOException {
        Reader reader = null;
        reader = new InputStreamReader(stream, "UTF-8");
        String result = null;
        char[] buffer = new char[128];
        int len = 0;
        while ((len = reader.read(buffer)) != -1){
            result = result + new String(buffer,0,len);
        }
        return result;
    }

    public String checkAccount(String userid,String password) throws IOException {
//        String result = null;
//        if(userid.equals("wc")&&password.equals("123456")){
//            result = "{\"status\":0,\"data\":{\"result\":\"true\",\"realname\":\"系统管理员\",\"userId\":\"xtgly\"}}";
//        }else {
//            result = "{\"status\":0,\"data\":{\"result\":\"false\",\"realname\":\"null\",\"userId\":\"null\"}}";
//        }

        String action = "mobile/login";
        String result = OpenURL(host+action+"?"+"name="+userid+"&"+"password="+password);

        if(result.startsWith("null")){
            result = result.substring(4);
        }
        Log.e("OpenUrl",result);
        return result;
    }

    public String loadList(String s) throws IOException {
        String action = "mobile/task/list/pub";
        String result = OpenURL(host + action);
        if(result.startsWith("null")){
            result = result.substring(4);
        }
        return result;
    }

    public String loadList(String id,int page,int status) throws IOException {
        String action1 = null;
        switch (page){
            case 0:
                action1 = load_all;
                break;
            case 1:
                action1 = load_member;
                break;
            case 2:
                action1 = load_my;
                break;
            default:
                action1 = load_all;
        }
        String action2 = null;
        switch (status){
            case 0:
                action2 = published;
                break;
            case 1:
                action2 = finished;
                break;
            case 2:
                action2 = evaluated;
                break;
            default:
                action2 = published;
        }

        String result = OpenURL(host + action1+action2+"?userId="+userId);
        if(result.startsWith("null")){
            result = result.substring(4);
        }
        return result;
    }

    public String loadDetail(String TaskId) throws IOException {
        String result = OpenURL(host+load_detail+"/"+TaskId);
        if(result.startsWith("null")){
            result = result.substring(4);
        }

//        String result = "{\"status\":0,\"data\":{\"taskId\":27,\"taskTitle\":\"1111111\",\"taskDetail\":\"qqweeeee\",\"startDate\":\"2015-05-21\",\"endDate\":\"2015-05-22\",\"pubDate\":\"2015-05-21\",\"evaluation\":null,\"status\":0,\"taskUser\":[{\"workerName\":\"宋孟岐\",\"everyDetail\":\"qwwrerr\"}]}}";
        return result;
    }

    public String loadWorkers(String getUserId) throws IOException {
//        String result = "{\"status\":0,\"data\":[{\"workerId\":8,\"workerName\":\"张桂海\",\"workDep\":\"安调部（安全）\"},{\"workerId\":9,\"workerName\":\"李四\",\"workDep\":\"安调部（安全）\"}]}";

        String action = get_workers_part1 + userId + get_workers_part2;
        String result = OpenURL(host+action);
        if(result.startsWith("null")){
            result = result.substring(4);
        }
        return result;
    }

    public String PublishToServer(String data) throws IOException {
        String jdata = URLEncoder.encode(data,"UTF-8");

        String result = OpenURL(host + publish_to_server + "?jdata="+jdata+"&userId="+userId);
        if(result.startsWith("null")){
            result = result.substring(4);
        }
        return result;
    }

    public void showToast(Context context,String msg){
        Looper.prepare();
        Toast.makeText(context,msg,Toast.LENGTH_SHORT).show();
        Looper.loop();
    }
}
